package com.fortune.rainshine.aspect;

import com.fortune.rainshine.feign.common.RedisFeign;
import com.fortune.rainshine.feign.service.ProductFeign;
import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.enums.ExceptionEnum;
import com.fortune.rainshinecommon.enums.RedisConstantEnum;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.exceptions.SignException;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @ClassName: TokenHttpAspect
 * @Description: TokenAOP验证
 * @author zhangxin
 * @date 2019年3月20日
 */
@Aspect
@Component
public class TokenHttpAspect {

    /**
     * 打印日志 slf4j
     */
    private static final Logger logger= LoggerFactory.getLogger(TokenHttpAspect.class);
    
    @Autowired
	RedisFeign redisFeign;

    @Autowired
    ProductFeign productFeign;

    @Pointcut("execution(public * com.fortune.rainshine.feign.service.ProductFeign.*(..)) "
            + "|| execution(public * com.fortune.rainshine.controller.ProductSaleController.*(..))"
            + "|| execution(public * com.fortune.rainshine.controller.UserController.*(..))"
            + "|| execution(public * com.fortune.rainshine.controller.CardController.*(..))"
            + "|| execution(public * com.fortune.rainshine.controller.CustomerCardController.*(..))"
            + "|| execution(public * com.fortune.rainshine.controller.CustomerController.*(..))"
            + "|| execution(public * com.fortune.rainshine.controller.CustomerPayCardController.*(..))"
            + "|| execution(public * com.fortune.rainshine.controller.OrderController.*(..))"
            + "|| execution(public * com.fortune.rainshine.controller.PurchaseController.*(..))"
            + "|| execution(public * com.fortune.rainshine.controller.ServiceRecordController.*(..))"
            + "|| execution(public * com.fortune.rainshine.controller.VideoController.*(..))"
    )
    public void log(){

    }

    /**
     * AOP请求拦截(验证token,sign)
     * @param joinPoint
     */
    @Before("log()")
    public void dobefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        HttpServletResponse respone=attributes.getResponse();
        
        logger.info("[http_url] {}",request.getRequestURL());
        logger.info("[http_method] {}",request.getMethod());
        logger.info("[http_ip] {}",request.getRemoteAddr());
        logger.info("[class_method] {}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
        logger.info("[http_args] {}",joinPoint.getArgs());

//        String shopId = request.getHeader("shopId");
//        if(StringUtils.isBlank(shopId)){
//            throw new SignException(ExceptionEnum.MISSHEADER);
//        }

        String token = request.getHeader("token");
//        String sign = request.getHeader("sign");
        String userId = request.getHeader("userId");
//        String timestamp = request.getHeader("timestamp");
//        String sign1=null;
        
//        if(token!=null&&userId!=null&&sign!=null&&timestamp!=null){
        if(token != null && userId != null){
//        	sign1 = SignUtils.getSign(request,token,timestamp);
//        	if(!sign1.equals(sign)){
//                throw new SignException(ExceptionEnum.SIGNERROR);
//            }

        	String accessToken = redisFeign.get(RedisConstantEnum.TOKEN.getMessage() +userId).getData().toString();
        	if(!StringUtils.equals(token,accessToken)){
                respone.setStatus(202);
                logger.error("log dobefore token验证失败");
                throw new SignException(ExceptionEnum.TOKENERROR);
//                return new MsgModel(ExceptionEnum.TOKENERROR.getErrMsg(), ResultCode.FAILURE);
            }
        }else{
            respone.setStatus(202);
            logger.error("log dobefore token为空或者userId为空");
            throw new SignException(ExceptionEnum.MISSHEADER);
//            return new MsgModel(ExceptionEnum.MISSHEADER.getErrMsg(), ResultCode.FAILURE);
        }
//        return new MsgModel("成功", ResultCode.SUCCESS);
    }

    /**
     * 请求后记录行为等
     */
    @After("log()")
    public void doafter(){
    }

    /**
     * 返回后打印返回值
     * @param object
     */
    @AfterReturning(pointcut = "log()",returning = "object")
    public void doafterreturning(Object object){
        logger.info("【respone】={}",object.toString());
    }

}
